<template>
  <PageLayout full :page-style="pageStyle">
    <!--头部导航-->
    <template #header>
      <HeaderLayout show-back>
        <view>{{ $t('Navigator.My.MyCoupon.Title.Text') }}</view>
      </HeaderLayout>
    </template>

    <!--内容区域-->
    <PageLayout>
      <template #header>
        <!--顶部tab栏-->
        <view class="tab_view">
          <view
            class="tab_content"
            :class="{ active: currentIndex === index }"
            v-for="(title, index) in tabTitles"
            :key="index"
            @click="changeTab(index)"
          >
            <view class="tab_item">{{ title }}</view>
            <view class="tab_line"></view>
          </view>
        </view>
      </template>
      <!--优惠券列表-->
      <scroll-view class="content-view" scroll-y @scrolltolower="loadMoreData" upper-threshold="5">
        <!--暂无更多消息-->
        <view v-if="!isSkeleton" class="no-data">
          <view class="no-data-view">
            <image :src="netconfig.ASSETS_IMGURL + 'img_message_empty.png'" class="icon" />
            <view class="text">暂无优惠券</view>
          </view>
        </view>
        <view v-else class="coupon" v-for="(data, index) in couponList" :key="index">
          <!--优惠券信息-->
          <view class="coupon_detail">
            <!--左侧信息-->
            <view v-if="data.productCoupon" class="couponImg" :class="{ unavailable: data.status != 0 }">
              <view class="money">
                <text class="symbol">¥</text>
                <text class="amount">{{ data.discountAmount }}</text>
              </view>
              <view class="money_des">
                <view v-if="data.satisfyAmount">满{{ data.satisfyAmount }}可用</view>
                <view v-else>无限制</view>
              </view>
            </view>
            <!--指定商品可用-->
            <view v-else class="couponImg_special" :class="{ unavailable: data.status != 0 }">
              <view class="couponPrice">
                <image src="/pages/my/static/coupon/coupon_special_icon.png" mode="widthFix"></image>
              </view>
              <view class="money_des">
                <view>指定商品可用</view>
              </view>
            </view>
            <!-- 右侧信息-->
            <view class="right_detail">
              <!--标题信息-->
              <view class="right_title">
                <image
                  class="icon"
                  mode="widthFix"
                  :src="netconfig.ASSETS_IMGURL + 'Logo_Login_BOSCH.png'"
                  v-if="data.brand == 1 && data.productCoupon"
                ></image>
                <image
                  class="icon"
                  mode="widthFix"
                  :src="netconfig.ASSETS_IMGURL + 'Logo_Login_SIEMENS.png'"
                  v-if="data.brand == 0 && data.productCoupon"
                ></image>
                <text class="special_title" v-if="!data.productCoupon">商品券</text>
                <text class="title">{{ data.couponName }}</text>
              </view>
              <!--时间信息-->
              <view class="timedes">
                <view class="time_text">
                  {{ handleValidStartTime(data.validStartTime) }} - {{ handlevalidEndTime(data.validEndTime) }}</view
                >
                <TrackButton track-id="My.Coupon.List.ImmediateUse.Button.Text" :track-data="data">
                  <view
                    v-if="data.status == 0"
                    class="use_button"
                    :class="{ special_use: !data.productCoupon }"
                    @click="nowlyUse(index)"
                    >{{ $t('My.Coupon.List.ImmediateUse.Button.Text') }}</view
                  >
                </TrackButton>
              </view>
              <!--详细信息，展开更多按钮-->
              <view class="show_detail" @click="showMore(index)">
                <view class="detail_class">详细信息</view>
                <image
                  src="/pages/my/static/coupon/retract.png"
                  :class="{ kDown: !data.showDetail }"
                  class="show_more_button"
                ></image>
              </view>
            </view>
            <!--状态标记 已使用 已过期-->
            <view class="couponTypeIcon">
              <image :src="netconfig.ASSETS_IMGURL + 'used.png'" mode="widthFix" v-if="data.status == 1"></image>
              <image :src="netconfig.ASSETS_IMGURL + 'Expired.png'" mode="widthFix" v-if="data.status == 2"></image>
            </view>
          </view>

          <!--展开查看更多-->
          <view v-if="data.showDetail" class="coupon_tip">
            <view class="detailLabel">
              <text class="name">使用范围：</text>
              <text>{{ data.range }}</text>
            </view>
            <view v-if="data.detail && data.detail.length > 0" class="detailLabel">
              <text class="name">使用说明：</text>
              <text>{{ data.detail }}</text>
            </view>
          </view>
        </view>
        <view class="no-more-tips" v-if="isSkeleton && !hasMore">当前没有更多卡券</view>
      </scroll-view>
    </PageLayout>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import { onShow } from '@dcloudio/uni-app'
import { onLoad } from '@dcloudio/uni-app'
import { getUserCoupon, type UserCouponModel } from '../../../api/coupon'
import netconfig from '@/config/netconfig'
import TrackButton from '@/dataReport/components/TrackButton.vue'
import { showLoading } from '@/utils/mpHelper'
import { jumpMP } from '../../../utils/mpHelper'
import { cloneDeepWith } from 'lodash'
import { TrackType, trackEvent } from '@/dataReport/tracks'
const couponList = ref<UserCouponModel[] | undefined>([])
const tabTitles = ['未使用', '已使用', '已过期']
const tabButtonIds = ['My.Coupon.Not.Use', 'My.Coupon.Has.Used', 'My.Coupon.Has.Expired']
const pageStyle = {
  backgroundColor: '#F4F4F4',
}

let page = 1
let rows = 10
let type = 0

onBeforeMount(() => {})
onShow(() => {})
const currentIndex = ref(0)
const hasMore = ref(true)
const isSkeleton = computed(() => {
  return couponList.value ? couponList.value.length > 0 : false
})

//生命周期 加载
onLoad((options) => {
  loadCouponData(false)
})

/**
 * 请求优惠券数据
 * @param pullUp 是否是上拉加载更多
 */
async function loadCouponData(pullUp: boolean) {
  showLoading(async () => {
    let res = await getUserCoupon(page, rows, type)
    if (res.code != 0) {
      uni.showToast({
        title: res.msg,
      })
    } else {
      if (!pullUp) {
        // 非上拉加载
        couponList.value?.splice(0, couponList.value.length)
        couponList.value = cloneDeepWith(res.data?.rows)
      } else {
        // 上拉加载的数据
        if (res.data?.rows) {
          couponList.value?.push(...res.data?.rows)
        }
      }
      // 获取是否有更多数据
      let total = res.data ? res.data?.total : 0
      let currentCount = couponList.value ? couponList.value?.length : 0
      let hasMoreFlag = total > currentCount
      hasMore.value = hasMoreFlag
    }
  })
}

/**
 * 更改切换index
 * @param index
 */
function changeTab(index: number) {
  // 数据埋点
  let track_data = {
    tab_name: tabTitles[index],
  }
  trackEvent('switch_coupon_tab', track_data, TrackType.BusinesssScene, tabButtonIds[index])
  // 重复点击不触发数据请求
  if (index == currentIndex.value) {
    return
  }
  currentIndex.value = index
  page = 1
  type = index
  loadCouponData(false)
}
/**
 * 处理start时间
 * @param validStartTime
 */
function handleValidStartTime(validStartTime: string) {
  let result = validStartTime
    ? `${validStartTime.substr(0, 4)}.${validStartTime.substr(4, 2)}.${validStartTime.substr(6, 2)}`
    : ''
  return result
}
/**
 * 处理end时间
 * @param validEndTime
 */
function handlevalidEndTime(validEndTime: string) {
  let result = validEndTime
    ? `${validEndTime.substr(0, 4)}.${validEndTime.substr(4, 2)}.${validEndTime.substr(6, 2)}`
    : ''
  return result
}

/**
 * 展示更多
 */
function showMore(index: number) {
  if (couponList.value && couponList.value.length > 0) {
    couponList.value[index].showDetail = !couponList.value[index].showDetail
  }
}

/**
 * 上拉加载更多
 */
function loadMoreData() {
  if (!hasMore.value) {
    return
  }
  page++
  loadCouponData(true)
}

/**
 * 立即使用
 * @param index
 */
function nowlyUse(index: number) {
  const appids = ['wx00e2750add150103', 'wx9498873cd6c2028e']
  if (couponList.value && couponList.value.length > 0) {
    let brand = couponList.value[index].brand
    let path = couponList.value[index].loadingPage
    jumpMP(appids[brand], path, {}, 'My.Coupon.Now.Use')
  }
}
</script>

<style scoped lang="less">
// 设置
.container {
  font-family: 'PingFang SC';
  font-style: normal;
  margin: 32rpx 0rpx;
}

.content-view {
  height: 100%;
  box-sizing: border-box;
}

.tab_view {
  display: flex;
  height: 108rpx;
  justify-content: space-around;
  align-items: flex-end;
  background: #ffffff;
  .tab_content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .tab_item {
      color: var(--dark-color);
      opacity: 0.6;
      font-family: PingFang SC;
      font-size: 32rpx;
      font-weight: 500;
    }
    .tab_line {
      width: 68rpx;
      height: 4rpx;
      margin-top: 8rpx;
      background-color: transparent;
    }
    &.active {
      .tab_item {
        font-weight: 500;
        opacity: 1;
      }
      .tab_line {
        background-color: var(--dark-color) !important;
      }
    }
  }
}
scroll-view {
  // background-color: #d9d9d9;
  margin-top: 32rpx;
}

.coupon_detail {
  display: flex;
  position: relative;
  height: 212rpx;
  box-sizing: border-box;
  background: url('/pages/my/static/coupon/coupon_couponBg.png') no-repeat;
  background-size: 100% 100%;
}
.coupon_tip {
  overflow: hidden;
  /* margin: 0 40rpx; */
  font-size: 24rpx;
  color: #9397aa;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: #f9f9f9;
  box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
}
.detailLabel {
  line-height: 34rpx;
  margin-bottom: 8rpx;
  display: flex;
  align-items: flex-start;
  .name {
    white-space: nowrap;
  }
}

.couponImg {
  flex: 0 0 220rpx;
  width: 234rpx;
  height: 212rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  background: url('/pages/my/static/coupon/coupon_blue.png') no-repeat;
  background-size: 100% 100%;
  .money {
    color: #fff;
    font-family: PingFang SC;
    font-style: normal;
    font-weight: 600;
    .symbol {
      font-size: 24rpx;
    }
    .amount {
      margin-left: 8rpx;
      font-size: 79.2rpx;
    }
  }
}
.couponImg_special {
  flex: 0 0 220rpx;
  width: 234rpx;
  height: 212rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  background: url('/pages/my/static/coupon/coupon_special.png') no-repeat no-repeat;
  background-size: 100% 100%;
}
.right_detail {
  flex: 1;
  margin: 0 40rpx;
  .right_title {
    height: 100rpx;
    padding-top: 10rpx;
    box-sizing: border-box;
    overflow: hidden;
    .icon {
      width: 120rpx;
      height: auto;
      /* height: 36rpx; */
      display: inline-block;
      margin-right: 16rpx;
      vertical-align: middle;
    }
    .special_title {
      color: #375de6;
      text-align: center;
      font-family: PingFang SC;
      font-size: 24rpx;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
      letter-spacing: 4rpx;
      width: 92rpx;
      height: 38rpx;
      margin-right: 32rpx;
    }
    .title {
      font-size: 28rpx;
      font-weight: 400;
      color: #131b35;
      line-height: 32rpx;
      vertical-align: middle;
    }
  }
}
.timedes {
  display: flex;
  align-self: center;
  justify-content: space-between;
  height: 68rpx;
  border-bottom: 1px dashed #e4e4e4;
  box-sizing: border-box;
  align-items: center;
  .time_text {
    color: #656b7b;
    font-family: PingFang SC;
    font-size: 20rpx;
    font-style: normal;
    font-weight: 400;
  }
  .use_button {
    width: 136rpx;
    height: 48rpx;
    border-radius: 23rpx;
    background-color: var(--primary-color);
    color: #ffffff;
    font-family: PingFang SC;
    font-size: 24rpx;
    font-style: normal;
    font-weight: 400;
    text-align: center;
    line-height: 48rpx;
  }
  .special_use {
    background-color: #375de6;
  }
}
.show_detail {
  height: 42rpx;
  display: flex;

  justify-content: space-between;
  align-items: center;
  .detail_class {
    color: #717687;
    font-family: PingFang SC;
    font-size: 20rpx;
    font-style: normal;
    font-weight: 400;
  }
  .show_more_button {
    width: 20rpx;
    height: 22rpx;
  }
}
.couponTypeIcon {
  position: absolute;
  width: 112rpx;
  right: 16rpx;
  top: 16rpx;
  image {
    width: 136rpx;
    height: 136rpx;
  }
}

.unavailable {
  background: url('/pages/my/static/coupon/coupon_gray.png') no-repeat;
  background-size: 100% 100%;
}

.no-data-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  .icon {
    width: 275px;
    height: 428rpx;
  }
  .text {
    font-size: 28rpx;
    margin-top: 48rpx;
    color: rgba(45, 55, 70, 1);
  }
}
.no-more-tips {
  width: 100%;
  color: #b8bac2;
  font-size: 14px;
  text-align: center;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}
.couponPrice {
  display: flex;
  font-size: 80rpx;
  font-weight: 600;
  align-items: flex-end;
  margin-bottom: 30rpx;
  image {
    width: 78rpx;
    height: auto;
  }
}
.coupon {
  margin-bottom: 32rpx;
  margin-left: 32rpx;
  margin-right: 32rpx;
}

.kDown {
  transform: rotate(180deg);
}
</style>
